package com.java.web;

import com.java.dao.commDao;
import com.java.dao.commDaoImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @Author xyd
 * @Date 2021/12/23 20:39
 * @Version 1.0
 */
public class editProductServlet extends HttpServlet {

    private commDao commDao = new commDaoImpl();


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String imageUrl = "";
        String[] str = new String[6];
        //获取图片
        //先判断上传的数据是否是多段
        String path0 = request.getRealPath("temp");
        System.out.println(path0);
        if (ServletFileUpload.isMultipartContent(request)){
            //创建工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                List<FileItem> list = servletFileUpload.parseRequest(request);

                //循环判断每一个表单项是普通类型还是上传的文件
                int i = 0;
                for (FileItem fileItem:list){
                    if (fileItem.isFormField()){
                        str[i++] = fileItem.getString("UTF-8");
                    }else {
                        File f = new File(path0);
                        if(!f.exists()){
                            f.mkdirs();
                        }
//                      System.out.println(fileItem.getFieldName());
                        fileItem.write(new File(path0+"\\"+fileItem.getName()));
                        imageUrl ="/temp/"+fileItem.getName();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.out.println(Arrays.toString(str));

            commDao.updateComm(Integer.parseInt(str[0]),str[1],Integer.parseInt(str[2]),Integer.parseInt(str[3]),str[4],str[5],imageUrl);
            request.setAttribute("err","<h4><font color='green'>修改成功!</font></h4>");
            request.getRequestDispatcher("/admin/products/list.jsp").forward(request, response);
        }
    }
}
